﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Input;
using Labthink.PCSoft.UniversalHost4.DataAccess;
using Labthink.PCSoft.UniversalHost4.Model;
using Labthink.PCSoft.UniversalHost4.Model.User;
using Labthink.PCSoft.UniversalHost4.UserControls.MsgBox;
using Labthink.PCSoft.UniversalHost4.Utility;

namespace Labthink.PCSoft.UniversalHost4
{
    public partial class AddUser
    {
        private const string RegMail =
            @"^[a-zA-Z0-9]+([._\\-]*[a-zA-Z0-9])*@([a-zA-Z0-9]+[-a-zA-Z0-9]*[a-zA-Z0-9]+.){1,63}[a-zA-Z0-9]+$";

        private const string RegTell =
            @"((\d{11})|(\d{10})|^((\d{7,8})|(\d{4}|\d{3})-(\d{7,8})|(\d{4}|\d{3})-(\d{7,8})-(\d{4}|\d{3}|\d{2}|\d{1})|(\d{7,8})-(\d{4}|\d{3}|\d{2}|\d{1}))$)";

        private UserInfo _info;

        private Window _owner;

        public string ActionMsg { get; set; }

        public UserInfo Info
        {
            get => _info;
            set
            {
                _info = value;
                TxtTitle.Text = LanguageManager.GetLanguageValue("ModifyUserWindowTitle");
            }
        }

        public AddUser()
        {
            InitializeComponent();
            DataContext = this;
        }

        private void btnOK_OnClick(object sender, RoutedEventArgs e)
        {
            txtUserID.Txt_OnLostFocus(null, null);
            txtUsername.Txt_OnLostFocus(null, null);
            if (string.IsNullOrEmpty(txtUserID.Value) ||
                string.IsNullOrEmpty(txtUsername.Value) ||
                cboRoles.SelectedIndex < 0)
                return;

            if (!string.IsNullOrEmpty(txtTel.Value))
            {
                if (!Regex.IsMatch(txtTel.Value, RegTell))
                {
                    MyMessageBox.Show(_owner, LanguageManager.GetLanguageValue("TelNotMatch"));
                    return;
                }
            }

            if (!string.IsNullOrEmpty(txtMail.Value))
            {
                if (!Regex.IsMatch(txtMail.Value, RegMail))
                {
                    MyMessageBox.Show(_owner, LanguageManager.GetLanguageValue("MailNotMatch"));
                    return;
                }
            }

            var ui = new UserInfo
            {
                LoginName = txtUserID.Value,
                UserName = txtUsername.Value,
                Role = ((ComboData)cboRoles.SelectedItem).Id,
                Email = txtMail.Value,
                Phone = txtTel.Value,
                Gender = 0,
            };

            if (_info != null)
            {
                ui.Id = _info.Id;

                try
                {
                    UserRepository.UpdateUser(ui);
                    LogRepository.AddLog(LanguageManager.GetLanguageValue("OP-UpdateUserSuccess", ui.LoginName), "Manage");
                    DialogResult = true;
                    ActionMsg = LanguageManager.GetLanguageValue("Success_ModifyUser");
                    Close();
                }
                catch (Exception ex)
                {
                    MyMessageBox.Show(_owner, ex.Message);
                }
            }
            else
            {
                try
                {
                    UserRepository.AddUser(ui);
                    LogRepository.AddLog(LanguageManager.GetLanguageValue("OP-AddUser", ui.LoginName), "Manage");
                    DialogResult = true;
                    ActionMsg = LanguageManager.GetLanguageValue("Success_AddUser");
                    Close();
                }
                catch (Exception ex)
                {
                    MyMessageBox.Show(_owner, ex.Message);
                }
            }
        }

        private void AddUser_OnLoaded(object sender, RoutedEventArgs e)
        {
            _owner = GetWindow(this);
            GetRoles();
            if (_info != null)
            {
                txtUserID.Value = _info.LoginName;
                txtUserID.IsEnabled = false;
                txtUsername.Value = _info.UserName;
                txtMail.Value = _info.Email;
                txtTel.Value = _info.Phone;
            }
        }

        private bool GetRoles()
        {
            // 获取并绑定角色列表
            List<Role> roles = RoleAndPerRepository.GetRoles();
            if (roles == null || !roles.Any())
            {
                return false;
            }

            var listData = new List<ComboData>();
            foreach (Role ro in roles)
            {
                listData.Add(new ComboData { Id = ro.Id, Value = ro.Name });
            }

            cboRoles.Init(listData, "Value", "Id");
            cboRoles.CbbChildBox.SelectedIndex = 0;
            if (_info != null)
            {
                cboRoles.SelectedValue = _info.Role;
            }

            return true;
        }

        private void BtnCancel_OnClick(object sender, RoutedEventArgs e)
        {
            Close();
        }

        private void Window_MouseDown(object sender, MouseButtonEventArgs e)
        {
            if (e.LeftButton == MouseButtonState.Pressed) DragMove();
        }

        private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
        {
            Close();
        }
    }
}
